package com.example.broad.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

/**
 * @author: snjgm
 * data: 2022/7/25
 * description:
 */
public class AlarmReceiver extends BroadcastReceiver {

    public static final String ALARM_ACTION = "ALARM";

    private final Context mContext;

    public AlarmReceiver(Context context) {
        super();
        this.mContext = context;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getAction().equals(ALARM_ACTION)) {
            Log.d("TAG", "收到一个闹钟广播");
            sendAlarm();
        }
    }

    //发送闹钟广播
    public void sendAlarm() {
        Intent intent = new Intent(ALARM_ACTION);
        //创建一个用于广播的延迟意图
        PendingIntent broadcast = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        //从系统服务中获取闹钟管理器
        AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 2000, broadcast);
            //设置一次性闹钟，延迟若干秒之后，携带延迟意图发送闹钟广播（但Android6.0之后，屏幕暗屏不保证发送广播）
            //必须调用setAndAllowWhileIdle方法;
            alarmManager.set(AlarmManager.RTC_WAKEUP, 2000, broadcast);
        }
    }
}
